package com.ruiyi.adrobot.mongo.accountInfo.impl;

import com.ruiyi.adrobot.beans.AccountInfo;
import com.ruiyi.adrobot.mongo.accountInfo.AccountInfoOperations;
import com.ruiyi.adrobot.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.LinkedList;
import java.util.List;

import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
import static org.springframework.data.mongodb.core.query.Criteria.where;

/**
 * Created by tao.zeng on 2017/7/18.
 */
public class AccountInfoRepositoryImpl implements AccountInfoOperations {
    @Autowired
    private MongoOperations mongo;

    @Override
    public AccountInfo.Account findRandomAccount(Integer fun, String model, Boolean virtual, String startDate, String endDate, List<String> usedImeis) {
        List<AggregationOperation> aggregationOperations = new LinkedList<>();
        aggregationOperations.add(Aggregation.match(Criteria.where("_id").is(fun)));
        aggregationOperations.add(Aggregation.unwind("accounts"));
        if (null != model) {
            aggregationOperations.add(Aggregation.match(Criteria.where("accounts.model").is(model).and("accounts.virtual").is(virtual).and("accounts.imei").nin(usedImeis).and("accounts.createDate").gt(startDate).lt(endDate)));
        } else {
            aggregationOperations.add(Aggregation.match(Criteria.where("accounts.virtual").is(virtual).and("accounts.imei").nin(usedImeis).and("accounts.createDate").gt(startDate).lt(endDate)));
        }
        aggregationOperations.add(Aggregation.project().and("accounts.userName").as("userName").and("accounts.pwd").as("pwd").and("accounts.imei").as("imei"));
        List<AccountInfo.Account> accounts = mongo.aggregate(newAggregation(aggregationOperations), "accountInfo", AccountInfo.Account.class).getMappedResults();
        if (accounts.size() > 0) {
            return accounts.get(RandomUtil.nextInt(accounts.size()));
        } else {
            return null;
        }

    }

    @Override
    public void appendAccount(Integer fun, AccountInfo.Account account) {
        Query query = new Query(Criteria.where("_id").is(fun));
        Update update = new Update();
        update.push("accounts", account);
        AccountInfo accountInfo = mongo.findOne(query, AccountInfo.class, "accountInfo");
        if (null == accountInfo) {
            mongo.insert(new AccountInfo(fun));
        }
        mongo.updateFirst(query, update, AccountInfo.class);
    }
}
